import axios from 'axios'
import { MessageBox, Message } from 'element-ui'

window.isDoingLogin = false

// 添加响应拦截器
axios.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response
  },
  function (error) {
    if (error.response) {
      if (![500, 404, 400].includes(error.response.status)) {
        if (error.response.status == 406) {
          location.replace('/store/login')
        } else {
          MessageBox.confirm([401, 402].includes(error.response.status) ? error.response.data.error : '系统错误,请联系管理员处理', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning',
            center: true,
            showClose: true,
            showCancelButton: false,
            closeOnClickModal: false
          }).then(() => {
            localStorage.removeItem('authorization')
            location.replace('/store/login')
          })
        }
      } else if ([500].includes(error.response.status)) {
        let errMsg = error.response.data.error
        let errMap = new Map([
          ['connect ETIMEDOUT', '请求超时，请重试']
        ])
        Message.error(errMap.get(errMsg) || errMsg)
      } else {
        Message.error(error.response.data.error)
      }
    } else {
      location.replace('/store/login')
    }

    // 对响应错误做点什么
    return Promise.reject(error)
  }
)
export default {
  install (Vue, options) {
    Vue.prototype.$command = {
      execute: this.executeCommand,
    }
  },
  async executeCommand (
    option = {
      method,
      api,
      data,
      params,
      headers: {},
      hideMsg: false
    }
  ) {
    var headers = Object.assign({
      'content-type': 'application/json',
      Authorization: localStorage.getItem('store/Authorization') ? `Bearer ${localStorage.getItem('store/Authorization')}` : undefined,
    }, option.headers)

    let response = await axios({
      method: option.method || 'post',
      url: '/base' + option.api,
      data: option.data,
      params: option.params,
      headers,
      withCredentials: true,
    })

    return new Promise((resolve, reject) => {
      let { flag, code, msg, message } = response.data
      if (flag && code == 200) {
        if (response.headers && response.headers.authorization) {
          localStorage.setItem('store/Authorization', response.headers.authorization)
        }
        resolve(response.data)
        return
      } else if (code == 5) {
        //未登录
        if (confirm('请先登录')) {
          //保存当前地址，登陆成功后将跳转到此处
          var gotoUrl = window.sessionStorage.getItem('goto-url')
          if (!gotoUrl) {
            window.sessionStorage.setItem('goto-url', location.href)
          }
          gApp.$router.replace({
            name: 'login',
          })
        }
      } else if (response.data.code == 500) {
        Message.error(msg)
      } else if (!flag && !option.hideMsg) {
        Message.error(message)
      }
      return reject(response.data)
    })
  },
}
